// pages/mine/chatHistory/chatSessionDetail/chatSessionDetail.js
let api = require("../../../../config/api");
let utils = require("../../../../utils/util");

Page({

    /**
     * 页面的初始数据
     */
    data: {
        conversationId: '',
        conversationName: '',
        userModelId: '',
        type: 'dialog', // 'dialog'(智能对话) 或 'image'(智能生图)
        messages: [],
        loading: false,
        hasMore: true,
        firstId: null,
        scrollTop: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const conversationId = options && options.conversationId ? decodeURIComponent(options.conversationId) : '';
        const name = options && options.name ? decodeURIComponent(options.name) : '';
        const type = options && options.type ? decodeURIComponent(options.type) : 'dialog';
        this.setData({ 
            conversationId: conversationId, 
            conversationName: name,
            type: type
        });
        this.bootstrap();
    },

    bootstrap() {
        let that = this;
        utils.isLogin(function(){
            wx.showLoading();
            utils.request(api.getUserInfo, {}, 'POST')
                .then(function(res){
                    wx.hideLoading();
                    if (res.code == 0) {
                        const info = res.data || {};
                        const modelId = info.modelUserId ? String(info.modelUserId) : '';
                        that.setData({ userModelId: modelId }, () => {
                            that.resetAndLoad();
                        });
                    } else {
                        wx.showToast({ title: res.message || '获取用户信息失败', icon: 'none' });
                    }
                })
                .catch(function(e){
                    wx.hideLoading();
                    wx.showToast({ title: e || '网络异常', icon: 'none' });
                });
        });
    },

    resetAndLoad() {
        this.setData({ messages: [], firstId: null, hasMore: true }, () => {
            this.loadMore();
        });
    },

    // 加载会话历史消息（倒序返回，前端按时间正序渲染）
    loadMore() {
        if (this.data.loading || !this.data.hasMore) return;
        if (!this.data.userModelId || !this.data.conversationId) return;
        this.setData({ loading: true });

        const base = api.dify && api.dify.base ? api.dify.base : '';
        const url = base + '/messages';
        // 根据type选择不同的api-key
        const isDialog = this.data.type === 'dialog';
        const apiKey = isDialog ? api.dify.dialogApiKey : api.dify.apiKey;
        const headers = {
            'Authorization': 'Bearer ' + apiKey
        };
        const params = {
            user: this.data.userModelId,
            conversation_id: this.data.conversationId,
            limit: 20
        };
        if (this.data.firstId) params.first_id = this.data.firstId;

        wx.request({
            url: url,
            method: 'GET',
            header: headers,
            data: params,
            success: (res) => {
                try {
                    if (res.statusCode === 200 && res.data && Array.isArray(res.data.data)) {
                        const pageList = res.data.data || [];
                        // 接口倒序返回：最新在最前。为了按时间正序显示，先反转。
                        const normalized = pageList.slice().reverse().map((msg) => ({
                            id: msg.id,
                            type: msg.answer ? 'ai' : 'user',
                            content: msg.answer ? msg.answer : (msg.query || ''),
                            time: (typeof msg.created_at === 'number' && msg.created_at > 0) ? this.formatTs(msg.created_at) : ''
                        }));
                        const merged = [...this.data.messages, ...normalized];
                        const firstId = pageList.length > 0 ? pageList[0].id : this.data.firstId;
                        const hasMore = !!res.data.has_more;
                        this.setData({ messages: merged, firstId: firstId, hasMore: hasMore, loading: false }, () => {
                            this.scrollToBottom();
                        });
                    } else {
                        this.setData({ loading: false, hasMore: false });
                        console.warn('messages unexpected response', res);
                    }
                } catch (e) {
                    this.setData({ loading: false });
                    console.warn('parse messages failed', e);
                }
            },
            fail: (err) => {
                this.setData({ loading: false });
                wx.showToast({ title: '加载失败', icon: 'none' });
            }
        });
    },

    scrollToBottom() {
        this.setData({ scrollTop: Date.now() });
    },

    formatTs(seconds) {
        const d = new Date(seconds * 1000);
        const pad = (n) => (n < 10 ? '0' + n : '' + n);
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const day = pad(d.getDate());
        const hh = pad(d.getHours());
        const mm = pad(d.getMinutes());
        return `${y}-${m}-${day} ${hh}:${mm}`;
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.loadMore();
    }
})